package com.zsy.oauth2.config.service;

import com.google.common.collect.Lists;
import com.zsy.base.bean.DemoResult;
import com.zsy.base.constant.Constants;
import com.zsy.dao.model.TbPermission;
import com.zsy.dao.model.TbUser;
import com.zsy.oauth2.config.dto.CustomUser;
import com.zsy.provider.api.feign.UacFeignApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * 自定义用户认证与授权
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    UacFeignApi uacFeignApi;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        DemoResult<TbUser> result = uacFeignApi.getUserByUserName(username);
        if (!Constants.SUCCESS.equals(result.getCode())){
            throw new UsernameNotFoundException("未获取到用户信息，msg："+result.getMsg());
        }

        TbUser tbUser = result.getData();
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        if (tbUser != null) {
            // 获取用户授权
            //List<TbPermission> tbPermissions = uacFeignApi.selectPermissionsByUserId(tbUser.getId());
            DemoResult listDemoResult = uacFeignApi.selectPermissionsByUserId(tbUser.getId());
            if (!Constants.SUCCESS.equals(listDemoResult.getCode())){
                return new User(tbUser.getUserName(), tbUser.getPassWord(), grantedAuthorities);
            }
            List<TbPermission> tbPermissions =(List<TbPermission>)listDemoResult.getData();
            // 声明用户授权
            tbPermissions.forEach(tbPermission -> {
                if (tbPermission != null && tbPermission.getEnname() != null) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(tbPermission.getEnname());
                    grantedAuthorities.add(grantedAuthority);
                }
            });
        }

       // return new User(tbUser.getUserName(), tbUser.getPassWord(),grantedAuthorities);

        //一下是为了扩展jwt信息
        CustomUser customUser = new CustomUser(tbUser.getUserName(), tbUser.getPassWord(), grantedAuthorities);
        customUser.setId(tbUser.getId().toPlainString());
        customUser.setName(tbUser.getUserName());

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("email",tbUser.getEmail());
        hashMap.put("phone",tbUser.getPhone());
        customUser.setOtherUserInfoParam(hashMap);

        return customUser;
    }
}
